#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanPuyangxianPolicy(BaseTaxPolicySpider):
    name = 'henan_puyangxian1_policy'
    
    province = '河南省'
    city = '濮阳市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['濮阳市濮阳县人民政府', "濮阳县", "https://www.puyangxian.gov.cn/column/index/id/15"],
            ['濮阳市濮阳县人民政府', "濮阳县", "https://www.puyangxian.gov.cn/column/index/id/203"],
            ['濮阳市清丰县人民政府', "清丰县", "http://www.qingfeng.gov.cn/class.asp?class=142"],
            ['濮阳市清丰县人民政府', "清丰县", "http://www.qingfeng.gov.cn/class.asp?class=144"],
            ['濮阳市台前县人民政府', "台前县", "http://www.taiqian.gov.cn/xxgk/list.asp?class=65"],
            ['濮阳市台前县人民政府', "台前县", "http://www.taiqian.gov.cn/xxgk/list.asp?class=75"],
            ['濮阳市人民政府', "", "https://www.puyang.gov.cn/zwxx/zwxx_list.asp?class=112"],
            ['濮阳市人民政府', "", "https://www.puyang.gov.cn/zwxx/zwxx_list.asp?class=120"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
            "//ul[contains(@class, 'pageList') or contains(@id, 'lbContainer')]//li//a[contains(@href, '.htm') or @title]/ancestor::li[string-length(string(.))>=5] |"
            "//tr[not(@id)]//td/a[contains(@href, 'id=')]/ancestor::td[string-length(string(.))>=10]"
        ):
            item = Item()
            item['source_url'] = elem.xpath("""./a/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.pdf' in item['source_url'] or '.doc' in item['source_url']:
                continue
            if '/id' not in item['source_url'] and 'id=' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        next_url = response.xpath("""//a[text()='下页' or .//text()='下一页' or text()='»']/@href""").get()
        if next_url and next_url not in ['javascript:void(0);']:
            # url = response.url.split(next_url.split('/')[0])[0] + next_url
            print(response.url, 'next', next_url)
            yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item}, dont_filter=True)
        else:
            print('not next_url', response.url)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//*[contains(.//text(), '发布日期：') or contains(.//text(), '发布时间：')]//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_puyangxian1_policy".split())
